package com.huohuzhihui.web.controller.agent;

import com.huohuzhihui.common.annotation.Log;
import com.huohuzhihui.common.constant.UserConstants;
import com.huohuzhihui.common.core.controller.BaseController;
import com.huohuzhihui.common.core.domain.AjaxResult;
import com.huohuzhihui.common.core.domain.entity.SysDept;
import com.huohuzhihui.common.core.domain.entity.SysUser;
import com.huohuzhihui.common.core.domain.model.LoginUser;
import com.huohuzhihui.common.enums.BusinessType;
import com.huohuzhihui.common.utils.SecurityUtils;
import com.huohuzhihui.common.utils.ServletUtils;
import com.huohuzhihui.common.utils.StringUtils;
import com.huohuzhihui.framework.web.service.TokenService;
import com.huohuzhihui.system.service.ISysDeptService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.List;

/**
 * 部门信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/agent/agent")
public class AgentController extends BaseController {
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private TokenService tokenService;

    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('agent:agent:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept) {
        dept.setDeptType(1);
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('agent:agent:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext()) {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('agent:agent:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId) {
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept) {
        dept.setDeptType(1);
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }


    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('agent:agent:add')")
    @Log(title = "代理商管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept, HttpServletRequest request) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("新增代理商'" + dept.getDeptName() + "'失败，代理商名称已存在");
        }
        if(dept.getParentId()==null){
            //设置上级部门为当前登陆用户
            LoginUser loginUser = tokenService.getLoginUser(request);
            SysUser sysUser = loginUser.getUser();

            dept.setParentId(sysUser.getDeptId());
        }
        //部门类型=1为代理商
        dept.setDeptType(1);
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('agent:agent:edit')")
    @Log(title = "代理商管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("修改代理商'" + dept.getDeptName() + "'失败，代理商名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return AjaxResult.error("修改代理商'" + dept.getDeptName() + "'失败，上级代理商不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
            return AjaxResult.error("该代理包含未停用的下级代理或商户！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('agent:agent:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return AjaxResult.error("存在下级代理或商户,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return AjaxResult.error("存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }

    /**
     * 查询商户抖音信息
     */
    @PreAuthorize("@ss.hasPermi('agent:agent:douyin')")
    @GetMapping(value = "getMerDouyin/{{deptId}}")
    public AjaxResult getMerDouyin(@PathVariable Long deptId) {

        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 充值
     */
    @PreAuthorize("@ss.hasPermi('agent:agent:recharge')")
    @GetMapping("/recharge")
    public AjaxResult recharge(SysDept dept) {
    /*    SysDept dept1 = this.deptService.selectDeptById(dept.getDeptId());
        int videoCount = dept1.getVideoCount();

        //充值后视频余额为原来余额新增当前充值套餐额度
        dept.setVideoCount(videoCount + dept.getVideoCount());*/
        return AjaxResult.success(deptService.rechargeVideoCount(dept.getDeptId(), dept.getVideoCount()));
    }

    /**
     * 获取代理商我的账户
     */
    @GetMapping("/myAgent")
    public AjaxResult myMerchant(SysDept dept) {
        //只查询当前商户的
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();

        dept.setDeptId(sysUser.getDeptId());
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

}
